import React, {Component} from 'react';
import {Switch as ReactSwitch, __RouterContext as RouterContext, matchPath} from "react-router";

export default class Switch extends ReactSwitch {

    static defaultProps = {
        renderAllChildren: false
    };

    render() {
        if (!this.props.renderAllChildren) {
            return super.render();
        }
        return (
            <RouterContext.Consumer>
                {context => {
                    let children = [];
                    let hasFind = false;
                    const location = this.props.location || context.location;
                    React.Children.forEach(this.props.children, child => {
                        if (React.isValidElement(child)) {
                            if (hasFind) {
                                children.push(React.cloneElement(child, {location, _switchItemMatch: false}));
                            } else {
                                const path = child.props.path || child.props.from;
                                hasFind = path
                                    ? matchPath(location.pathname, {...child.props, path})
                                    : context.match;
                                children.push(React.cloneElement(child, {location, computedMatch: hasFind}));
                            }
                        } else {
                            children.push(child);
                        }
                    });
                    return children;
                }}
            </RouterContext.Consumer>
        );
    }
}
